<!-- 催缴通单列表 -->
<template>
  <div class="collection-notice-container">
    <el-tabs v-model="activeTab" type="line" class="tab-container">
      <el-tab-pane label="当月应缴" name="current">
        <el-card class="filter-card">
          <el-form :inline="true" :model="queryParams" class="filter-form">
            <el-form-item label="载体">
              <el-select
                v-model="queryParams.zt"
                placeholder="请选择载体"
                clearable
                style="width: 200px"
              >
                <el-option label="联健元和" value="联健元和" />
                <el-option label="达博" value="达博" />
                <el-option label="科澜项目" value="科澜项目" />
                <el-option label="国科项目" value="国科项目" />
                <el-option label="黄埭项目" value="黄埭项目" />
                <el-option label="金扶梯" value="金扶梯" />
                <el-option label="北联新翼" value="北联新翼" />
                <el-option label="深圳项目" value="深圳项目" />
                <el-option label="西山项目" value="西山项目" />
                <el-option label="秦淮项目" value="秦淮项目" />
                <el-option label="双创中心" value="双创中心" />
                <el-option label="创界项目" value="创界项目" />
                <el-option label="江环项目" value="江环项目" />
                <el-option label="江北项目" value="江北项目" />
                <el-option label="拓展项目" value="拓展项目" />
                <el-option label="试点项目" value="试点项目" />
              </el-select>
            </el-form-item>
            <el-form-item label="企业名称" prop="companyName">
              <el-input
                v-model="queryParams.companyName"
                placeholder="请输入企业名称"
                clearable
                style="width: 220px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="合同编号" prop="contractNumber">
              <el-input
                v-model="queryParams.contractNumber"
                placeholder="请输入合同编号"
                clearable
                style="width: 220px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item v-if="activeTab === 'current'" label="应缴费年月">
              <el-date-picker
                v-model="queryParams.startTime"
                type="month"
                placeholder="请选择年月"
                format="YYYY年MM月"
                value-format="YYYY年MM月"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 统计信息卡片 -->
        <el-card class="statistics-card" style="margin-top: 18px" v-loading="loading">
          <div class="statistics-container">
            <div class="stat-item">
              <div class="stat-label">{{ queryParams.startTime || "当月" }}应缴数</div>
              <div class="stat-value">{{ total }}</div>
            </div>
            <div class="stat-divider"></div>
            <div class="stat-item">
              <div class="stat-label">总应缴金额</div>
              <div class="stat-value amount">¥{{ formatAmount(amountTotal) }}</div>
            </div>
            <div class="stat-divider"></div>
            <div class="stat-item">
              <div class="stat-label">总剩余金额</div>
              <div class="stat-value remaining">
                ¥{{ formatAmount(remainingAmountTotal) }}
              </div>
            </div>
            <div class="stat-divider"></div>
            <div class="stat-item">
              <div class="stat-label">总已付金额</div>
              <div class="stat-value paid">¥{{ formatAmount(paidAmountTotal) }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">已付金额占比</div>
              <div class="stat-value arrears">{{ percentage }}%</div>
            </div>
          </div>
        </el-card>

        <el-card class="list-card" style="margin-top: 18px">
          <el-table v-loading="loading" :data="list" style="width: 100%" border>
            <el-table-column
              prop="companyName"
              label="所属公司"
              width="350"
              show-overflow-tooltip
              align="left"
            >
              <template #default="scope">
                <span
                  :style="{ color: scope.row.remainingAmount > 0 ? 'blue' : 'red' }"
                  >{{ scope.row.companyName }}</span
                >
              </template>
            </el-table-column>
            <el-table-column prop="cycle" label="缴费周期" width="300" align="left" />
            <el-table-column
              prop="startTime"
              label="应缴费用时间"
              width="150"
              align="left"
            />
            <el-table-column prop="amount" label="总金额" width="120" align="left" />
            <el-table-column
              prop="remainingAmount"
              label="剩余金额"
              width="120"
              align="left"
            />
            <el-table-column
              prop="paidAmount"
              label="已付金额"
              width="120"
              align="left"
            />
            <el-table-column prop="type" label="费用类型" width="100" align="left" />
            <el-table-column
              prop="contractNumber"
              label="合同编号"
              width="320"
              show-overflow-tooltip
              align="left"
            />
            <el-table-column prop="unitPrice" label="单价" width="180" align="left" />
            <el-table-column
              prop="monthPrice"
              label="月度费用"
              width="180"
              align="left"
            />

            <el-table-column
              prop="remake"
              label="备注"
              width="250"
              show-overflow-tooltip
              align="left"
            />
            <!-- 操作列  -->
            <el-table-column label="操作" width="120" fixed="right" align="left">
              <template #default="{ row }">
                <el-button type="primary" link @click="handlePayment(row)"
                  >缴费</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="欠款账单" name="arrears">
        <el-card class="filter-card">
          <el-form :inline="true" :model="queryParams" class="filter-form">
            <el-form-item label="载体">
              <el-select
                v-model="queryParams.zt"
                placeholder="请选择载体"
                clearable
                style="width: 200px"
              >
                <el-option label="联健元和" value="联健元和" />
                <el-option label="达博" value="达博" />
                <el-option label="科澜项目" value="科澜项目" />
                <el-option label="国科项目" value="国科项目" />
                <el-option label="黄埭项目" value="黄埭项目" />
                <el-option label="金扶梯" value="金扶梯" />
                <el-option label="北联新翼" value="北联新翼" />
                <el-option label="深圳项目" value="深圳项目" />
                <el-option label="西山项目" value="西山项目" />
                <el-option label="秦淮项目" value="秦淮项目" />
                <el-option label="双创中心" value="双创中心" />
                <el-option label="创界项目" value="创界项目" />
                <el-option label="江环项目" value="江环项目" />
                <el-option label="江北项目" value="江北项目" />
                <el-option label="拓展项目" value="拓展项目" />
                <el-option label="试点项目" value="试点项目" />
              </el-select>
            </el-form-item>
            <el-form-item label="企业名称" prop="companyName">
              <el-input
                v-model="queryParams.companyName"
                placeholder="请输入企业名称"
                clearable
                style="width: 220px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="合同编号" prop="contractNumber">
              <el-input
                v-model="queryParams.contractNumber"
                placeholder="请输入合同编号"
                clearable
                style="width: 220px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="应缴费年月">
              <el-date-picker
                v-model="queryParams.startTime"
                type="month"
                placeholder="请选择年月"
                format="YYYY年MM月"
                value-format="YYYY年MM月"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 统计信息卡片 -->
        <el-card class="statistics-card" style="margin-top: 18px" v-loading="loading">
          <div class="statistics-container">
            <div class="stat-item">
              <div class="stat-label">欠款账单数</div>
              <div class="stat-value">{{ total }}</div>
            </div>
            <div class="stat-divider"></div>
            <div class="stat-item">
              <div class="stat-label">总应缴金额</div>
              <div class="stat-value amount">¥{{ formatAmount(amountTotal) }}</div>
            </div>
            <div class="stat-divider"></div>
            <div class="stat-item">
              <div class="stat-label">总剩余金额</div>
              <div class="stat-value remaining">
                ¥{{ formatAmount(remainingAmountTotal) }}
              </div>
            </div>
            <div class="stat-divider"></div>
            <div class="stat-item">
              <div class="stat-label">总已付金额</div>
              <div class="stat-value paid">¥{{ formatAmount(paidAmountTotal) }}</div>
            </div>
            <div class="stat-divider"></div>
            <div class="stat-item">
              <div class="stat-label">已付金额占比</div>
              <div class="stat-value arrears">{{ percentage }}%</div>
            </div>
          </div>
        </el-card>

        <el-card class="list-card" style="margin-top: 18px">
          <el-table v-loading="loading" :data="list" style="width: 100%" border>
            <el-table-column
              prop="companyName"
              label="所属公司"
              width="350"
              show-overflow-tooltip
              align="left"
            >
              <template #default="scope">
                <span
                  :style="{ color: scope.row.remainingAmount > 0 ? 'blue' : 'red' }"
                  >{{ scope.row.companyName }}</span
                >
              </template>
            </el-table-column>
            <el-table-column prop="cycle" label="缴费周期" width="300" align="left" />
            <el-table-column
              prop="startTime"
              label="应缴费用时间"
              width="150"
              align="left"
            />
            <el-table-column prop="amount" label="总金额" width="120" align="left" />
            <el-table-column
              prop="remainingAmount"
              label="剩余金额"
              width="120"
              align="left"
            />
            <el-table-column
              prop="paidAmount"
              label="已付金额"
              width="120"
              align="left"
            />
            <el-table-column prop="type" label="费用类型" width="100" align="left" />
            <el-table-column
              prop="contractNumber"
              label="合同编号"
              width="320"
              show-overflow-tooltip
              align="left"
            />

            <el-table-column prop="unitPrice" label="单价" width="180" align="left" />
            <el-table-column
              prop="monthPrice"
              label="月度费用"
              width="180"
              align="left"
            />

            <el-table-column
              prop="remake"
              label="备注"
              width="250"
              show-overflow-tooltip
              align="left"
            />
            <el-table-column label="操作" width="120" fixed="right" align="left">
              <template #default="{ row }">
                <el-button type="primary" link @click="handlePayment(row)"
                  >缴费</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </el-card>
      </el-tab-pane>
    </el-tabs>
    <PaymentModal
      v-model="showPaymentModal"
      :company-id="currentCompanyId"
      :plan-id="currentPlanId"
      @success="handlePaymentSuccess"
      @close="handlePaymentClose"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, getCurrentInstance } from "vue";
import {
  getPaymentPlanList,
  getArrearsList,
  insertPaymentHistory,
} from "@/api/company/info.js";
import PaymentModal from "@/views/Company/PaymentModal.vue";
const { proxy } = getCurrentInstance();
const loading = ref(false);
const total = ref(0);

// 统计信息
const amountTotal = ref(0); // 总金额
const paidAmountTotal = ref(0); // 总剩余金额
const remainingAmountTotal = ref(0); // 总已收金额
const percentage = ref(0); // 已付金额占比

const list = ref([]);
const activeTab = ref("current"); // 当前激活的tab

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  companyName: "", // 企业名称
  contractNumber: "", // 合同编号
  zt: "",
  startTime: getCurrentMonth(),
  status: undefined, // 状态 0-未回款，1-部分回款，2-欠款，3-完结, -1-未完结
});

// 缴费弹窗相关
const showPaymentModal = ref(false);
const currentCompanyId = ref("");
const currentPlanId = ref("");
const currentPlanInfo = ref({});
// 处理缴费操作
function handlePayment(row) {
  currentCompanyId.value = row.companyId;
  currentPlanId.value = row.id;
  showPaymentModal.value = true;
}

// 缴费成功回调
function handlePaymentSuccess() {
  // 重新刷新列表
  getList();
  // 关闭弹窗组件
  showPaymentModal.value = false;
}

// 关闭弹窗回调
function handlePaymentClose() {
  // 关闭弹窗组件
  showPaymentModal.value = false;
}
// 获取列表
function getList() {
  loading.value = true;

  amountTotal.value = 0; // 总金额
  paidAmountTotal.value = 0; // 总剩余金额
  remainingAmountTotal.value = 0; // 总已收金额
  percentage.value = 0; // 已付金额占比

  if (activeTab.value === "current") {
    // 当月应缴逻辑
    queryParams.status = -1; // 未完结
    getPaymentPlanList(queryParams)
      .then(handleResponse)
      .catch(handleError)
      .finally(() => (loading.value = false));
  } else {
    // 欠款账单逻辑
    queryParams.status = null; // 欠款状态
    // queryParams.startTime = ""; // 不限制时间
    getArrearsList(queryParams)
      .then(handleResponse)
      .catch(handleError)
      .finally(() => (loading.value = false));
  }
}

function handleResponse(res) {
  const ok = res && (res.code === 200 || res.rows);
  if (ok) {
    const rows = Array.isArray(res.rows) ? res.rows : [];
    list.value = rows;
    total.value = res.total || 0;

    if (res.extend) {
      amountTotal.value = res.extend.totalItem.amountTotal || 0;
      remainingAmountTotal.value = res.extend.totalItem.remainingAmountTotal || 0;
      paidAmountTotal.value = res.extend.totalItem.paidAmountTotal || 0;
      percentage.value = res.extend.totalItem.percentage || 0;
    }
  } else {
    list.value = [];
    total.value = 0;
  }
}

function handleError() {
  list.value = [];
  total.value = 0;
}

function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

function resetQuery() {
  queryParams.companyName = "";
  queryParams.contractNumber = "";
  queryParams.zt = "";
  queryParams.startTime = getCurrentMonth();
  queryParams.pageNum = 1;
  getList();
}
// 获取当前年月 YYYY年MM月
function getCurrentYearMonth() {
  const now = new Date();
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, "0");
  return `${year}年${month}月`;
}
// 获取当前月份（格式：YYYY年MM月）
function getCurrentMonth() {
  const now = new Date();
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, "0");
  return `${year}年${month}月`;
}

// 格式化金额，添加千分位分隔符
function formatAmount(amount) {
  if (!amount && amount !== 0) return "0.00";
  const num = Number(amount);
  if (isNaN(num)) return "0.00";
  return num.toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
}
// 监听tab切换
watch(activeTab, () => {
  queryParams.pageNum = 1;
  getList();
});

onMounted(() => {
  // 如果用户没有手动选择年月，则使用当前年月
  if (!queryParams.startTime) {
    queryParams.startTime = getCurrentYearMonth();
  }
  getList();
});
</script>

<style scoped>
.collection-notice-container {
  padding: 24px 32px 0 32px;
  min-height: 100vh;
}

.filter-card {
  margin-bottom: 12px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #f0f0f0;
}

.filter-form {
  padding: 8px 0 0 0;
}

.list-card {
  margin-bottom: 18px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #f0f0f0;
}

.el-table {
  border-radius: 8px;
  font-size: 15px;
}

.el-table th {
  color: #333;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
}

.el-table td {
  color: #444;
  border-bottom: 1px solid #f0f0f0;
}

.el-button[type="primary"] {
  background: linear-gradient(90deg, #4f8cff 0%, #38c8fa 100%);
  border: none;
  color: #fff;
  border-radius: 6px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(32, 159, 240, 0.08);
  transition: background 0.2s;
}

.el-button[type="primary"]:hover {
  background: linear-gradient(90deg, #2563eb 0%, #38c8fa 100%);
}

/* 统计信息卡片样式 */
.statistics-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #f0f0f0;
}

.statistics-container {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 16px 0;
  flex-wrap: wrap;
  gap: 16px;
}

.stat-item {
  flex: 1;
  min-width: 140px;
  text-align: center;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
  font-weight: 400;
  line-height: 20px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  line-height: 32px;
}

.stat-value.amount {
  color: #409eff;
}

.stat-value.remaining {
  color: #e6a23c;
}

.stat-value.paid {
  color: #67c23a;
}

.stat-divider {
  width: 1px;
  height: 48px;
  background: linear-gradient(
    180deg,
    transparent 0%,
    #e4e7ed 20%,
    #e4e7ed 80%,
    transparent 100%
  );
  margin: 0 8px;
}

@media (max-width: 1200px) {
  .stat-divider {
    display: none;
  }
  .statistics-container {
    justify-content: flex-start;
  }
  .stat-item {
    min-width: calc(50% - 8px);
  }
}
</style>
